#ifndef __WIN32__
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <netinet/in.h>     /* INADDR_ANY, sockaddr_in ... */
#include <string.h>
#include <errno.h>
#include <unistd.h>
#else
#include <winsock2.h>
#endif
#include "n1d_types.h"


#define SERVER_PORT     12456

#ifndef __WIN32__
#define closesocket(x)  close(x);
#define INVALID_SOCKET  (-1)
#define SOCKET_ERROR    (-1)
#define IPPROTO_UDP     17
#endif

extern volatile int gSIGHUP;
volatile SOCKET gSocket;

void n1log(const char* format, ...);

void n1server(void)
{
	sockaddr_in sockAddr;
    sockaddr_in recvAddr;
    int ret = 0;
    SOCKET _socket;
    gSocket = INVALID_SOCKET;
    
    _socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if(_socket==INVALID_SOCKET)
    {
        n1log("error in socket(). errno=%d", errno);
        return;
    }
    gSocket = _socket;

	memset(&sockAddr,0,sizeof(sockAddr));
	sockAddr.sin_family = AF_INET;
	sockAddr.sin_addr.s_addr = htonl(INADDR_ANY);
	sockAddr.sin_port = htons((u_short)12456);

	ret = ::bind(_socket, (sockaddr*)&sockAddr, sizeof(sockAddr));
	if(ret==SOCKET_ERROR)
	{
        n1log("error in bind(). errno=%d", errno);
        closesocket(_socket);
        return;
	}

	while(1)
	{
	    socklen_t len = sizeof(recvAddr);
	    char buff[1600];

        ret = ::recvfrom(_socket, (char*)buff, sizeof(buff), 0, (sockaddr*)&recvAddr, &len);
        if(ret==SOCKET_ERROR)
        {
            n1log("error in recvfrom(). errno=%d", errno);
            continue;
        }

        ret = ::sendto(_socket, buff, ret, 0, (sockaddr*)&recvAddr, len);
        if(ret==SOCKET_ERROR)
        {
            n1log("error in sendto(). errno=%d", errno);
        }
    }

    closesocket(_socket);
}
